package fun.werfamily.wf.order.core.domain.remote.facade;

import com.alibaba.fastjson.JSON;
import fun.werfamily.wf.base.vo.Result;
import fun.werfamily.wf.order.core.domain.dto.result.OrderDTO;
import fun.werfamily.wf.order.core.domain.remote.dto.PayCancelReq;
import fun.werfamily.wf.order.core.domain.remote.dto.PayCancelSuccessRespDTO;
import fun.werfamily.wf.order.core.domain.remote.dto.PayCreateReq;
import fun.werfamily.wf.order.core.domain.remote.dto.PaySuccessRespDTO;
import fun.werfamily.wf.order.core.domain.remote.service.PaymentRemoteService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: Mr.WenMing Zhang
 * @Date: 2022-08-28 17:33
 * @Description:
 */
@Component
@Slf4j
public class PaymentServiceFacade {
    @Resource
    private PaymentRemoteService paymentRemoteService;

    /**
     * 创建支付单
     *
     * @param orderDTO
     * @return
     */
    public PaySuccessRespDTO createPay(OrderDTO orderDTO) {
        PayCreateReq req = new PayCreateReq();
        req.setBizNo(orderDTO.getOrderNo());
        req.setUserCode(orderDTO.getUserCode());
        req.setRemark(orderDTO.getRemark());
        req.setPayAmount(orderDTO.getOrderAmount());
        req.setPayType("AILI_PAY_H5");
        req.setBizType(1);
        req.setCreateBy(orderDTO.getUserCode());
        req.setPayTime(LocalDateTime.now());
        try {
            Result<PaySuccessRespDTO> result = paymentRemoteService.createPay(req);
            log.info("调用payment-core创建支付单,req={},resp={}", JSON.toJSONString(req), JSON.toJSONString(result));
            if (result.isSuccess()) {
                return result.getData();
            }
        } catch (Exception e) {
            log.error("调用payment-core创建支付单，异常req={}", JSON.toJSONString(orderDTO), e);
        }
        return null;
    }

    /**
     * 取消支付
     *
     * @param orderDTO
     * @return
     */
    public PayCancelSuccessRespDTO cancelPay(OrderDTO orderDTO) {
        PayCancelReq req = new PayCancelReq();
        req.setBizNo(orderDTO.getOrderNo());
        req.setUserCode(orderDTO.getUserCode());
        req.setRemark(orderDTO.getRemark());
        req.setPayAmount(orderDTO.getOrderAmount());
        req.setPayType("AILI_PAY_H5");
        req.setBizType(1);
        try {
            Result<PayCancelSuccessRespDTO> result = paymentRemoteService.cancelPay(req);
            log.info("调用payment-core取消支付,req={},resp={}", JSON.toJSONString(req), JSON.toJSONString(result));
            if (result.isSuccess()) {
                return result.getData();
            }
        } catch (Exception e) {
            log.error("调用payment-core取消支付，异常req={}", JSON.toJSONString(orderDTO), e);
        }
        return null;
    }
}
